package com.tina.util;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * Created by liuyangkly on 15/6/27.
 * 使用了google zxing作为二维码生成工具
 */
public class ZxingUtils {
    private static Log log = LogFactory.getLog(ZxingUtils.class);

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;
    private static final String codeFormat = "UTF8";
    private static final String imgFormat = "png";

    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    private static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    /**
     * 将内容contents生成长宽均为width的图片，图片路径由imgPath指定
     */
    public static File getQRCodeImge(String contents, int width, String imgPath) {
        return getQRCodeImge(contents, width, width, imgPath);
    }

    /**
     * 将内容contents生成长为width，宽为width的图片，图片路径由imgPath指定
     */
    public static File getQRCodeImge(String contents, int width, int height, String imgPath) {
        try {
            Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.CHARACTER_SET, codeFormat);

            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);

            File imageFile = new File(imgPath);
            writeToFile(bitMatrix, imgFormat, imageFile);

            return imageFile;
        } catch (Exception e) {
            log.error("create QR code error!", e);
            return null;
        }
    }

    /***
     * 生成带logo的二维码
     * @param contents
     * @param width
     * @param imgPath
     * @param logo
     * @return
     * @throws IOException
     */
    public static File getQRCodeLogoImge(String contents, int width, String imgPath, File logo) throws IOException {
        File qrCodeImge = getQRCodeImge(contents, width, width, imgPath);
        return createLogoCode(qrCodeImge, logo, imgPath);
    }

    /**
     * @param qrCodeImge 二维码生成的原图地址
     * @param lgoImg     需要插入LOGO图地址
     * @param imgPath    图片路径由imgPath指定
     * @return
     * @throws IOException
     */
    public static File createLogoCode(File qrCodeImge, File lgoImg, String imgPath) throws IOException {
        //读取二维码图片
        BufferedImage bufferedImage = ImageIO.read(qrCodeImge);
        //获取画笔
        Graphics2D graphics = bufferedImage.createGraphics();
        //读取logo图片
        BufferedImage logo = ImageIO.read(lgoImg);
        //设置二维码大小，太大了会覆盖二维码，此处为20%
        int logoWidth = logo.getWidth() > bufferedImage.getWidth() * 2 / 10 ? (bufferedImage.getWidth() * 2 / 10) : logo.getWidth();
        int logoHeight = logo.getHeight() > bufferedImage.getHeight() * 2 / 10 ? (bufferedImage.getHeight() * 2 / 10) : logo.getHeight();
        //设置logo图片放置的位置，中心
        int x = (bufferedImage.getWidth() - logoWidth) / 2;
        int y = (bufferedImage.getHeight() - logoHeight) / 2;
        //开始合并并绘制图片
        graphics.drawImage(logo, x, y, logoWidth, logoHeight, null);
        graphics.drawRoundRect(x, y, logoWidth, logoHeight, 15, 15);
        //logob边框大小
        graphics.setStroke(new BasicStroke(1));
        //logo边框颜色
        graphics.setColor(Color.WHITE);
        graphics.drawRect(x, y, logoWidth, logoHeight);
        graphics.dispose();
        logo.flush();
        bufferedImage.flush();
        File file = new File(imgPath);
        ImageIO.write(bufferedImage, imgFormat, file);
        return file;
    }




}
